<?php

namespace App\Listener;

use App\Event\ConsumeEvent;
use App\Event\RechargeEvent;
use App\Helpers\ConfigUtil;
use App\Model\Act\InviteRewardLog;
use App\Model\CoinLog;
use App\Model\GiftLog;
use App\Model\Setting\TmpSetting;
use App\Model\UserCoin;
use App\Model\UserProfile;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * 充值邀请活动监听
 * @Listener 
 */
class InviteRewardListener implements ListenerInterface
{
    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            //充值事件
            RechargeEvent::class,
            //消费事件
            ConsumeEvent::class,
        ];
    }

    /**
     * @param UserRegistered $event
     */
    public function process(object $event)
    {
        //被邀请人
        $userId = $event->eventType == 'recharge' ? $event->userId : $event->hostUserId;
        $orderId = $event->eventType == 'recharge' ? $event->orderId : '';

        //获取邀请人profileId
        $profile = UserProfile::getProfile($userId);
        if (!$profile) return false;
        //被邀请人注册时间
        $invitedRegTime = (string)$profile->created_at;
        $inviteUserProfileId = intval($profile->invite_code);

        //无人邀请
        if (!$inviteUserProfileId) return false;

        $inviteUser = UserProfile::getInfoByProfileId($inviteUserProfileId);
        if (!$inviteUser) return false;
	$inviteUserId = $inviteUser->user_id;

	//如果是男用户邀请
        $invite_profile = UserProfile::getProfile($inviteUserId);
        if ($invite_profile->gender == 1) return false;

        switch ($event->eventType) {
            case 'recharge':
                //充值额分成
                $baseCoin = $event->rechargeCoin;
                $rewardCoin = $this->getInviteRewardCoin($baseCoin, 'recharge', $inviteUserId, $invitedRegTime);
                //邀请类型
                $inviteLogType = InviteRewardLog::TYPE_RECHARGE;
                //来源
                $coinLogFrom = CoinLog::FROM_INVITE_RECHARGE;
                break;

            case 'consume':
                //收入分成
                $baseCoin = $event->incomeCoin;
                $rewardCoin = $this->getInviteRewardCoin($baseCoin, 'consume', $inviteUserId, $invitedRegTime);
                //邀请类型
                $inviteLogType = InviteRewardLog::TYPE_CONSUME;
                //来源
                $coinLogFrom = $event->logFrom;
                break;
            default:
                return;
        }
        //小于0.1金币不处理
        if ($rewardCoin < 0.1) return;

        //是否邀请奖励
        if ($this->checkDoReward($inviteUser, $profile, $event->eventType, $rewardCoin)) {
            //邀请记录
            InviteRewardLog::addRecord($inviteUserId, $userId, $rewardCoin, $inviteLogType);
            //更新收入账户
            $remainCoin = UserCoin::gainIncome($inviteUserId, $rewardCoin);
            //账户流水
            CoinLog::addIncome($inviteUserId, $rewardCoin, $coinLogFrom, $remainCoin, $orderId, $userId);
            log_user_result($inviteUserId, "Event:{$event->eventType}=={$userId}==Base:{$baseCoin}==Reward:{$rewardCoin}==DoReawrd");
        } else {
            $remainCoin = UserCoin::getUserInfo($inviteUserId);
            //加入记录
            CoinLog::addExtraIncome($inviteUserId, $rewardCoin, $coinLogFrom, $remainCoin, $orderId, $userId);
            log_user_result($inviteUserId, "Event:{$event->eventType}=={$userId}==Base:{$baseCoin}==Reward:{$rewardCoin}==PassReward");
        }
    }

    /**
     * 计算邀请奖励金额
     */
    function getInviteRewardCoin(
        $baseCoin = 0,
        $type = 'consume',
        $inviteUserId = 0,
        $invitedRegTime = ''
    ) {
        $percent = ConfigUtil::getInviteReward($type);
        //活动时间
        $this->actPercent($percent, $type, $invitedRegTime);
        log_user_result($inviteUserId, "Type:{$type}==InvitePercent:{$percent}");
        return round($percent * $baseCoin, 1);
    }

    /**
     * 活动额外邀请奖励
     */
    function actPercent(&$percent = 0, $type = 'consume', $invitedRegTime = '')
    {
        $actConfigs = config('act.invite.act');
        $time = date('Y-m-d H:i:s');
        foreach ($actConfigs as $actConfig) {
            if (!$actConfig['enable']) continue;
            $startTime = $actConfig['valid_time'][0];
            $endTime = $actConfig['valid_time'][1];
            if (
                $time < $startTime
                || $time > $endTime
                || ($invitedRegTime && $invitedRegTime < $startTime)
            ) continue;
            if (!isset($actConfig['reward_' . $type])) continue;
            $percent += $actConfig['reward_' . $type];
        }
        return $percent;
    }

    /**
     * 该单是否奖励
     */
    function checkDoReward(
        $inviteUser = null,
        $profile = null,
        $eventType = 'recharge',
        $rewardCoin = 0
    ) {
        if ($eventType != 'recharge') return true;
        if (!TmpSetting::getRewardFilter()) return true;
        $rewardUserId = $inviteUser->user_id;
        $invitedUserId = $profile->user_id;
        //白名单主播
        $whiteIds = explode(',', env('INVITE_REWARD_WHITE_ID', ''));
        if (in_array($rewardUserId, $whiteIds)) return true;
        //1、注册时间早于N天 + 奖励金币小于N
        $offDay = TmpSetting::getRewardExpDay();
        $offDate = date('Y-m-d', strtotime("- {$offDay} day"));
        $regTime = date('Y-m-d', strtotime((string)$profile->created_at));
        $passRewardCoin = env('INVITE_REWARD_PASS_COIN', 100);
        if (
            TmpSetting::getRewardSubFilter(1)
            && $regTime < $offDate
            && $rewardCoin <= $passRewardCoin
        ) {
            log_user_result($rewardUserId, "{$invitedUserId}==RewardCoin:{$rewardCoin}==RegTime:{$regTime}==Pass1");
            return false;
        }

        //2、上次送礼的人不是邀请者
        $giftLog = GiftLog::checkLastLog($invitedUserId, 30);
        if (
            TmpSetting::getRewardSubFilter(2)
            && $giftLog
            && $giftLog->receive_user_id != $rewardUserId
            && $rewardCoin <= $passRewardCoin
        ) {
            log_user_result($rewardUserId, "{$invitedUserId}==RewardCoin:{$rewardCoin}==Pass2");
            return false;
        }

        //3、总共的邀请奖励间隔
        // $rewardCount = InviteRewardLog::getRewardCount(
        //     $rewardUserId,
        //     $invitedUserId,
        //     InviteRewardLog::TYPE_RECHARGE
        // );
        // $offCount = TmpSetting::getRewardOffCount();
        // if (
        //     $rewardCount > 0
        //     && $offCount > 0
        //     && $rewardCount % $offCount == 0
        //     && $rewardCoin <= $passRewardCoin
        // ) {
        //     log_user_result($rewardUserId, "{$invitedUserId}==RewardCount:{$rewardCount}==OffCount:{$offCount}==Pass3");
        //     return false;
        // }
        return true;
    }
}
